<?php
namespace app\admin\controller;

use app\admin\common\controller\Base;
use app\admin\common\model\Department as departmentModel;
use think\facade\Request;
use   PhpOffice\PhpSpreadsheet\IOFactory ; 
use   PhpOffice\PhpSpreadsheet\Cell\Coordinate ; 
use   PhpOffice\PhpSpreadsheet\Spreadsheet ; 
use   PhpOffice\PhpSpreadsheet\Writer\Xlsx ; 
use think\Db;

class Department extends Base
{
    public function index()
    {
        $departmentId = Request::param('department_id');
        if($departmentId=='1')
        {
            $departmentId="职能部门";
            $departmentList=departmentModel::where('type',$departmentId)
            ->order('weight desc')
            ->paginate(10);
        }
        elseif($departmentId=='2')
        {
            $departmentId="教学院系";
            $departmentList=departmentModel::where('type',$departmentId)
            ->order('weight desc')
            ->paginate(10);
        }
        else{
            $departmentList=departmentModel::order('weight desc')
            ->paginate(10);
        }
        $this->view->assign('departmentList',$departmentList);
        $this->view->assign('title','部门&院系');
        return $this->view->fetch();
    }
    
    //执行删除
    public function doDelete()
    {
        //1，获取当前要删除的主键id
        $id=Request::param('id');
        //2，执行删除
        if(departmentModel::where('id',$id)->delete())
        {
            return $this->success('删除成功','admin/Department/index');
        }
        else
        {
            return $this->error('删除失败','admin/Department/index');
        }
    }
    
    //用户编辑
    public function departmentEdit()
    {
        //1，获取当前更新的用户的主键
        $departmentId=Request::param('id');
        $department_id=Request::param('department_id');
        //2，根据主键进行查询
        $departmentInfo=departmentModel::where('id',$departmentId)->find();
        //3，设置编辑界面的模板变量
        $this->view->assign('title','更改部门&院系信息');
        $this->view->assign('departmentInfo',$departmentInfo);
        $this->view->assign('department_id',$department_id);
        $this->view->assign('title','部门&院系');
        //4，渲染出编辑页面
        return $this->view->fetch('departmentEdit');
    }
    
    //执行用户编辑的信息
    public function doEdit()
    {
        //1，获取到用户提交的信息
        $data=Request::post();
        $department_id=$data['department_id'];
        $data=Request::except('department_id','post');
        //2，取出主键    
        $id=$data['id'];
        //4，删除主键id，只有删除主键之后才能将新的数据加入到数据表中
        unset($data['id']);
        //5，执行更新操作
        if(departmentModel::where('id',$id)->data($data)->update())
        {
            return $this->success('更新成功',url('admin/Department/index',['department_id'=>$department_id]));
        }  
    }
    
    //添加数据验证
    public function insertDepartment(){
        if ( Request::isAjax() ) {
            //使用模型来创建数据
            //验证数据
            $data = Request::post(); //要插入的数据
            if ( $user = departmentModel::create( $data ) ) {
                    return [ 'status' => 1, 'message' => '插入数据成功' ];
                } else {
                    return [ 'status' => 0, 'message' => '插入数据失败' ];
                }             
        } else {
            $this->error( "请求类型错误", 'admin/Department/index' );
        }
    }
//    文件导出
   public function output()
   {
//    $data = [
//        ['title1' => '111', 'title2' => '222'],
//        ['title1' => '111', 'title2' => '222'],
//        ['title1' => '111', 'title2' => '222']
//    ];
/*
php版本在5.1.20之后DB类才是可以使用 WithAttr 方法的。
    $data=Db::table('ht_department')
        ->field(['name','type','campus','status','weight'])
        ->withAttr('status',function($value){
            $status=[0=>'禁用',1=>'启用'];
            return $status[$value];
        })
        ->select();
 */
       $res = departmentModel::field(['name','type','campus','status','weight'])->order('weight asc')->select();
//       数组转换为对象
       $data=json_decode(json_encode($res), true);
       
    $title = ['名称', '部门类型','所在校区','状态','权重'];
    // Create new Spreadsheet object
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
 
    // 方法二，使用 setCellValue
    //表头
    //设置单元格内容
    $titCol = 'A';
    foreach ($title as $key => $value) {
        // 单元格内容写入
        $sheet->setCellValue($titCol . '1', $value);
        $titCol++;
    }
    $row = 2; // 从第二行开始
    foreach ($data as $item) {
        $dataCol = 'A';
        foreach ($item as $value) {
            // 单元格内容写入
            $sheet->setCellValue($dataCol . $row, $value);
            $dataCol++;
        }
        $row++;
    }
 
    // Redirect output to a client’s web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="部门&院系管理.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
 
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
 
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output'); 
       exit;
   } 
    
    
    
    //	批量删除
		public function delete(){
			//	获取前台删除的全部id  (/a强制转换为数组类型)
			// 因为修改是根据主键id修改的  所以要用修饰符转换一下
			$data=input('ids/a');
			//	调用model里面的destroy方法 传参是删除的ID 
			$info = departmentModel::destroy($data);
			//	判断是否删除成功
			if($info){
				$this->success('批量删除成功');
			}else{
				$this->error('请在选择你要删除的内容');
			}
		}
    
    //模糊搜寻
    public function searchform()
    {
        $search=Request::post();
        $searchname=$search['searchname'];
        $form=$search['form'];
        $departmentInfo = departmentModel::where($form,'like','%' . $searchname . '%')->paginate(6);
        $this->assign('departmentInfo',$departmentInfo);
        if($form =='name'){
            $form = '名称';
        }
        if($form =='type'){
            $form = '部门类型';
        }
        if($form =='campus'){
            $form = '所在校区';
        }
        $this->assign('form',$form);
        $this->assign('searchname',$searchname);
        $this->view->assign('title','部门&院系');
        return $this->fetch('searchform');
        
    }

    public function namevalidte()
    {
        if(Request::isAjax()){
            $nameInput=input('nameInput');
            $res=departmentModel::where('name',$nameInput)->find();
            if($res){
                return ['status'=>1,'message'=>'名称已存在！'];
            }else{
                return ['status'=>0,'message'=>''];
            }
            
            
        }else{
            $this->error("请求类型出错",'admin/Department/index');
        }
    }
    
    //    模板下载
    public function templateDown()
    {
        $title = ['名称', '部门类型','所在校区','权重'];
        // Create new Spreadsheet object
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 方法二，使用 setCellValue
        //表头
        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        
        // Redirect output to a client’s web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="部门&院系模板.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
 
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
 
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output'); 
       exit;
        }
}